package com.leetcode;

import ds.ListNode;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No142
 * @description 环形链表2
 * @date 2021/2/26 下午5:15
 */
public class No142 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        ListNode l5 = new ListNode(5);
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;
        l5.next = l3;
        ListNode res = detectCycle(l1);
        if(res != null){
            System.out.println(res.val);
        }else{
            System.out.println("Empty");
        }

    }

    public static ListNode detectCycle(ListNode head){
        if(head == null || head.next == null){
            return null;
        }
        ListNode fast = head,slow = head;
        while (fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                break;
            }
        }
        if(fast == null || fast.next == null){
            return null;
        }
        ListNode pre = head;
        while (pre != slow){
            pre = pre.next;
            slow = slow.next;
        }
        return pre;
    }

}
